import { defineStore } from 'pinia'
import { store } from '/@/store'
import { THEME_KEY } from '@/enums/cacheEnum'
import { themeConfig } from '@/config/theme'
import { ThemeEnum } from '@/enums/themeEnum'
import { routerConfig } from '@/logics/router'

interface AppState {
  partnerId: string
  theme: ThemeEnum
}

export const useAppStore = defineStore({
  id: 'app-app',
  state: (): AppState => ({
    partnerId: '',
    theme: uni.getStorageSync(THEME_KEY),
  }),
  actions: {
    // 获取app基础信息
    async initApp() {
      this.partnerId = ''
    },
    /**
     * 主题切换
     * @param theme
     */
    async changeTheme(theme: ThemeEnum) {
      uni?.ToggleAppTheme && uni.ToggleAppTheme(theme)
      this.theme = theme
      this.changeSysTheme()
    },
    /**
     * 初始化主题
     */
    async changeSysTheme() {
      const { theme } = this
      const appTheme = theme || ThemeEnum.THEME_DEFAULT
      // 设置导航条
      themeConfig[appTheme]?.navBar &&
        uni.setNavigationBarColor(themeConfig[appTheme].navBar)
      // 只有当前是tabbar页面是才设置如何判断呢--获取当前的路由进行判断
      const pages = getCurrentPages()
      if (
        pages.length &&
        pages[0]?.route &&
        (routerConfig.tabbars as any).includes(pages[0].route)
      ) {
        // 设置tabbar
        themeConfig[appTheme]?.tabBar &&
          uni.setTabBarStyle(themeConfig[appTheme].tabBar)
      }
    },
  },
})

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useAppStore(store)
}
